<template>
  <el-card>
    <!-- 添加面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        <router-link to="/workflow">编排管理</router-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item>新建编排</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="workflow-form">
      <el-form
        ref="ruleFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="formData.templateName" placeholder="请输入模板名称" />
        </el-form-item>

        <el-form-item label="场景标签" prop="sceneTag">
          <el-select v-model="formData.sceneTag" filterable placeholder="请选择场景标签">
            <el-option
              v-for="item in tableData"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            />
            <template #footer>
              <div class="add-tag" @click="addTag" :value="'添加标签'" :key="'添加标签'">
                <span
                  ><el-icon class="add-icon"><CirclePlus /></el-icon>添加标签</span
                >
              </div>
            </template>
          </el-select>
        </el-form-item>

        <el-form-item label="场景描述" prop="sceneDescription">
          <el-input
            v-model="formData.sceneDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入场景描述"
          />
        </el-form-item>

        <el-form-item label="目标服务器" prop="targetServer">
          <el-select v-model="formData.targetServer" placeholder="请选择目标服务器" filterable>
            <el-option
              v-for="server in targetServers"
              :label="server.name"
              :value="server.id"
              :key="server.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :before-close="handleCloseDialog"
      :width="dialogWidth"
    >
      <AddTag
        v-if="rwType === 'add_tag'"
        @submit="handleSubmit"
        @close="handleCloseDialog"
        :edit-data="editData"
      ></AddTag>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineAsyncComponent } from 'vue';
import { useRouter } from 'vue-router';
import { CirclePlus } from '@element-plus/icons-vue';
import { tagList } from '@/api/tag';

const AddTag = defineAsyncComponent(() => import('@/views/scriptLibrary/form/addTag.vue'));
const router = useRouter();
const ruleFormRef = ref();
const dialogVisible = ref(false);
const rwType = ref('add_tag');
const dialogTitle = ref('新建标签');
const dialogWidth = ref('50%');
const editData: any = ref(null);

// 表单数据
const formData = reactive({
  templateName: '',
  sceneTag: '',
  sceneDescription: '',
  targetServer: '',
});

// 表单验证规则
const rules = reactive({
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
  ],
  sceneDescription: [{ max: 500, message: '场景描述最多500个字符', trigger: 'blur' }],
  targetServer: [{ required: true, message: '请选择目标服务器', trigger: 'change' }],
});

// 提交表单
const submitForm = async () => {
  if (!ruleFormRef.value) return;

  try {
    await ruleFormRef.value.validate();
    // 这里可以添加表单提交的逻辑
    console.log('表单数据:', formData);
    // 提交成功后返回列表页
    router.push('/workflow');
  } catch (error) {
    console.log('表单验证失败:', error);
  }
};

// 重置表单
const resetForm = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
};

// 模拟目标服务器数据
const targetServers = ref([
  { id: '1', name: '服务器A' },
  { id: '2', name: '服务器B' },
  { id: '3', name: '服务器C' },
]);

// 获取场景标签
const tableData = ref([] as any[]);
const getList = async () => {
  const res = await tagList();
  if (res.data.code === 200) {
    tableData.value = res.data.data;
  }
};
// 关闭弹窗
const handleCloseDialog = () => {
  dialogVisible.value = false;
  rwType.value = '';
  editData.value = null;
};
// 新建标签
const addTag = () => {
  dialogVisible.value = true;
  rwType.value = 'add_tag';
  dialogTitle.value = '新建标签';
  editData.value = null;
};
const handleSubmit = async () => {
  dialogVisible.value = false;
  rwType.value = '';
  dialogTitle.value = '';
  editData.value = null;
  // 刷新表格数据
  await getList();
  // 选中最新创建的标签
  if (tableData.value && tableData.value.length > 0) {
    const latestTag = tableData.value.reduce((prev, current) =>
      prev.id > current.id ? prev : current,
    );
    formData.sceneTag = latestTag.id;
    // 手动触发表单验证更新，避免验证错误提示
    if (ruleFormRef.value) {
      ruleFormRef.value.clearValidate('sceneTag');
    }
  }
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.add-workflow {
  padding: 20px;
}

.workflow-form {
  margin-top: 20px;
}

.demo-ruleForm {
  max-width: 600px;
}
.add-tag {
  border-top: 1px dashed #e4e7ed;
  background: #f8f9fa;
  cursor: pointer;
  height: 40px;
  line-height: 40px;
  text-indent: 10px;
  .add-icon {
    margin-right: 5px;
    font-size: 16px;
    color: #1890ff;
    vertical-align: sub;
  }
}

.add-tag:hover {
  background: #e6f7ff;
  color: #1890ff;
}
</style>
